package com.mall.server.service.sms;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.dubbo.api.SmsFlashPromotionApi;
import com.mall.dubbo.api.SmsFlashPromotionProductRelationApi;
import com.mall.dubbo.api.SmsFlashPromotionSessionApi;
import com.mall.model.domain.SmsFlashPromotion;
import com.mall.model.domain.SmsFlashPromotionProductRelation;
import com.mall.model.domain.SmsFlashPromotionSession;
import com.mall.model.vo.CommonPage;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SmsFlashPromotionService {

    @DubboReference
    private SmsFlashPromotionApi smsFlashPromotionApi;

    @DubboReference
    private SmsFlashPromotionSessionApi smsFlashPromotionSessionApi;

    @DubboReference
    private SmsFlashPromotionProductRelationApi smsFlashPromotionProductRelationApi;


    //根据活动名称分页查询
    public CommonPage list(String keyword, Integer pageNum, Integer pageSize) {

        Page<SmsFlashPromotion> page = smsFlashPromotionApi.findList(keyword, pageNum, pageSize);

        return new CommonPage(page);
    }

    //添加活动
    public void saveFlash(SmsFlashPromotion flashPromotion) {

        flashPromotion.setCreateTime(new Date());
        smsFlashPromotionApi.save(flashPromotion);
        List<SmsFlashPromotionSession> list = smsFlashPromotionSessionApi.findByCreateTime(flashPromotion.getStartDate(), flashPromotion.getEndDate());
        if (CollUtil.isNotEmpty(list)) {
            List<Long> ids = CollUtil.getFieldValues(list, "id", Long.class);
            List<SmsFlashPromotionProductRelation> relations = new ArrayList<>();
            for (Long id : ids) {
                SmsFlashPromotionProductRelation relation = new SmsFlashPromotionProductRelation();
                relation.setFlashPromotionId(flashPromotion.getId());
                relation.setFlashPromotionSessionId(id);
                relations.add(relation);
            }
            smsFlashPromotionProductRelationApi.saveBatch(relations);
        }

    }

    //删除活动
    public void deleteFlash(Integer id) {

        smsFlashPromotionApi.removeById(Long.valueOf(id));
    }

    //修改数据
    public void updateFlash(Integer id, SmsFlashPromotion smsFlashPromotion) {

        smsFlashPromotionApi.updateFlash(id, smsFlashPromotion);
    }


    //获取活动详情
    public SmsFlashPromotion findById(Integer id) {

        return smsFlashPromotionApi.getById(id);
    }

}

